import { createSlice } from "@reduxjs/toolkit";

import { request } from "../../utils/request";

const userStore = createSlice({
  name: "user",
  
  initialState: {
    token: localStorage.getItem("token") || "",
    userInfo: {},
  },
  reducers: {
    setToken(state, action) {
      state.token = action.payload;
      localStorage.setItem("token", action.payload);
    },
    setUserInfo(state, action) {
      state.userInfo = action.payload;//此处注意赋值别搞错了 state获取会出现
    },
    clearUserInfo(state){
        state.token=''
        state.userInfo={}
        localStorage.clear()
    }
  },
});

const fetchLogin = (loginform) => {
  return async (dispatch) => {
    const res = await request.post("/authorizations", loginform);
    dispatch(setToken(res.data.token));
  };
};
//获取个人信息
const fetchUserInfo = () => {
  return async (dispatch) => {
    const res =await  request.get("/user/profile");
   
    dispatch(setUserInfo(res.data));
  };
};
const { setToken, setUserInfo ,clearUserInfo} = userStore.actions;
const userReducer = userStore.reducer;

export { setToken, fetchLogin, fetchUserInfo,clearUserInfo };

export default userReducer;
